from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse

# Register your models here.
from .models import Article, ArticleGroup
from .models import Mission
from .models import TaskRelation
from .models import MissionDetail
from .models import MissionDetailTaskRelation
from .models import MissionBasicInfo, MissionContent, MissionStatus
from adminsortable2.admin import SortableInlineAdminMixin,SortableAdminBase

from .forms import TaskRelationForm
from .models import Astronaut
from .models import Encyclopedia
from .models import (
    Mission, MissionDetail, MissionBasicInfo, MissionContent, MissionStatus,
    MissionCrewMember, MissionDetailTaskRelation, Institution, MissionInstitutionMember,InstitutionRelation
)

# 为 MissionInstitutionMember 创建内联
class MissionInstitutionMemberInline(admin.TabularInline):
    model = MissionInstitutionMember
    extra = 1
    fields = ('institution', 'role', 'order')
    
    # 新增机构关联内联
class InstitutionRelationInline(admin.TabularInline):
    model = InstitutionRelation
    fk_name = 'from_institution'  # 指定外键字段
    extra = 1
    fields = ('to_institution', 'role', 'order')
    verbose_name = "相关机构"
    verbose_name_plural = "相关机构"
    autocomplete_fields = ['to_institution']


class MissionDetailTaskRelationInline(SortableInlineAdminMixin, admin.TabularInline):
    model = MissionDetailTaskRelation
    extra = 1  # 默认显示一个空白行以供添加
    #ordering = ['order']
    fields = ('task_relation',)  # 只显示任务组字段
    exclude = ('order',)  # 明确排除 order 字段

# 自定义 Article 的 Admin 界面
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    # 在列表页显示的字段
    list_display = ('id', 'title', 'column', 'date')
    
    # 添加搜索框，支持通过标题搜索
    search_fields = ('title',)
    
    # 设置默认排序方式（按日期从新到老排列）
    ordering = ('-date',)

# 自定义 Mission 的 Admin 界面
@admin.register(Mission)
class MissionAdmin(admin.ModelAdmin):
    # 在列表页显示的字段
    list_display = (
        'id',
        'mission_name',
        'institution',
        'launch_time',
        'status',
        'recommend',
        'is_displayable',
        'is_countable',
        'edit_mission_detail_link',
        'edit_basic_info_link',
        'edit_content_link',
        'edit_status_link',
    )
    
    # 添加只读字段，使编辑链接在表单页面显示
    readonly_fields = ('edit_mission_detail_link', 'edit_basic_info_link', 'edit_content_link', 'edit_status_link')
    
    # 设置编辑页面的字段布局
    fieldsets = (
        ('基本信息', {
            'fields': ('mission_name', 'institution', 'launch_time', 'launch_time_utc', 'status')
        }),
        ('图片信息', {
            'fields': ('image_url', 'header_image')
        }),
        ('设置', {
            'fields': ('recommend', 'is_displayable', 'is_countable')
        }),
        ('快速编辑链接', {
            'fields': ('edit_mission_detail_link', 'edit_basic_info_link', 'edit_content_link', 'edit_status_link'),
        }),
    )
    
    # 添加搜索框，支持通过任务名称和机构名称搜索
    search_fields = ('mission_name', 'institution',)
    
    # 添加过滤器，支持按状态、推荐字段、是否可展示和是否可统计过滤
    list_filter = ('status', 'recommend', 'is_displayable', 'is_countable')
    
    # 设置默认排序方式（按推荐状态优先，然后按发射时间倒序排列）
    ordering = ('-launch_time_utc','-recommend')
    
    # 添加自定义actions
    actions = ['copy_mission_with_details']

    @admin.action(description='复制选中的任务及其关联数据')
    def copy_mission_with_details(self, request, queryset):
        from django.db import transaction
        import copy
    
        copied_count = 0
        failed_missions = []
    
        for mission in queryset:
            try:
                with transaction.atomic():
                    # 1. 复制主任务，这将触发信号自动创建关联对象
                    new_mission = Mission.objects.create(
                        institution=mission.institution,
                        mission_name=f"{mission.mission_name} (副本)",
                        launch_time=mission.launch_time,
                        image_url=mission.image_url,
                        header_image=mission.header_image,
                        status=mission.status,
                        launch_time_utc=mission.launch_time_utc,
                        recommend=False,
                        is_displayable=mission.is_displayable,
                        is_countable=mission.is_countable
                    )
    
                    # 2. 更新由信号创建的 MissionDetail
                    try:
                        original_detail = mission.任务名称
                        new_detail = new_mission.任务名称  # 获取自动创建的实例
                        new_detail.launch_site = original_detail.launch_site
                        new_detail.save()
    
                        # 复制乘组成员关系
                        for crew_member in original_detail.missioncrewmember_set.all():
                            MissionCrewMember.objects.create(
                                mission_detail=new_detail,
                                astronaut=crew_member.astronaut,
                                role=crew_member.role,
                                order=crew_member.order
                            )
    
                        # 复制关联任务组关系
                        for task_relation in original_detail.missiondetailtaskrelation_set.all():
                            MissionDetailTaskRelation.objects.create(
                                mission_detail=new_detail,
                                task_relation=task_relation.task_relation,
                                order=task_relation.order
                            )
                        # 复制参与机构关系
                        for institution_member in original_detail.missioninstitutionmember_set.all():
                            MissionInstitutionMember.objects.create(
                                mission_detail=new_detail,
                                institution=institution_member.institution,
                                role=institution_member.role,
                                order=institution_member.order
                            )

                        # 复制关联的文章
                        new_detail.articles.set(original_detail.articles.all())

                        # 复制文章内容组
                        new_detail.article_group = original_detail.article_group
                        new_detail.save()
                        
                    except Mission.任务名称.RelatedObjectDoesNotExist:
                        # 如果原始任务没有详情，则不需要做任何事，因为信号已经创建了空的详情
                        pass
    
                    # 3. 更新由信号创建的 MissionBasicInfo
                    try:
                        original_basic_info = mission.basic_info
                        new_basic_info = new_mission.basic_info
                        new_basic_info.country = original_basic_info.country
                        new_basic_info.institution = original_basic_info.institution
                        new_basic_info.rocket_name = original_basic_info.rocket_name
                        new_basic_info.payload_info = original_basic_info.payload_info
                        new_basic_info.launch_site = original_basic_info.launch_site
                        new_basic_info.mini_tags = copy.deepcopy(original_basic_info.mini_tags)
                        new_basic_info.badge_url = original_basic_info.badge_url
                        new_basic_info.badge_text = original_basic_info.badge_text
                        new_basic_info.save()
                    except Mission.basic_info.RelatedObjectDoesNotExist:
                        pass
    
                    # 4. 更新由信号创建的 MissionContent
                    try:
                        original_content = mission.content_data
                        new_content = new_mission.content_data
                        new_content.content = copy.deepcopy(original_content.content)
                        new_content.save()
                    except Mission.content_data.RelatedObjectDoesNotExist:
                        pass
    
                    # 5. 更新由信号创建的 MissionStatus
                    try:
                        original_status = mission.status_data
                        new_status = new_mission.status_data
                        new_status.status = original_status.status
                        new_status.description = original_status.description
                        new_status.color = original_status.color
                        new_status.save()
                    except Mission.status_data.RelatedObjectDoesNotExist:
                        pass
    
                    copied_count += 1
    
            except Exception as e:
                failed_missions.append((mission.mission_name, str(e)))
    
        if copied_count > 0:
            self.message_user(request, f'成功复制了 {copied_count} 个任务。', level='SUCCESS')
    
        if failed_missions:
            for name, error in failed_missions:
                self.message_user(request, f'复制任务 "{name}" 失败: {error}', level='ERROR')

    copy_mission_with_details.short_description = "复制选中的任务及其关联数据"

    def edit_mission_detail_link(self, obj):
        """
        生成跳转到任务详情编辑页面的链接
        """
        if hasattr(obj, '任务名称'):
            url = reverse('admin:myapp01_missiondetail_change', args=[obj.任务名称.pk])
            return format_html('<a href="{}">编辑任务详情</a>', url)
        return "无任务详情"
    
    edit_mission_detail_link.short_description = "任务详情"
    
    def edit_basic_info_link(self, obj):
        """
        生成跳转到任务基本信息编辑页面的链接
        """
        if hasattr(obj, 'basic_info'):
            url = reverse('admin:myapp01_missionbasicinfo_change', args=[obj.basic_info.pk])
            return format_html('<a href="{}">编辑基本信息</a>', url)
        return "无基本信息"
    
    edit_basic_info_link.short_description = "基本信息"

    def edit_content_link(self, obj):
        """
        生成跳转到任务内容编辑页面的链接
        """
        if hasattr(obj, 'content_data'):
            url = reverse('admin:myapp01_missioncontent_change', args=[obj.content_data.pk])
            return format_html('<a href="{}">编辑任务简介</a>', url)
        return "无任务简介"
    
    edit_content_link.short_description = "内容"

    def edit_status_link(self, obj):
        """
        生成跳转到任务状态编辑页面的链接
        """
        if hasattr(obj, 'status_data'):
            url = reverse('admin:myapp01_missionstatus_change', args=[obj.status_data.pk])
            return format_html('<a href="{}">编辑状态卡片</a>', url)
        return "无状态卡片"
    
    edit_status_link.short_description = "状态"

# 在文件开头的 import 部分添加
from .models import MissionCrewMember
from adminsortable2.admin import SortableInlineAdminMixin

# 添加 MissionCrewMemberInline 类
class MissionCrewMemberInline(SortableInlineAdminMixin, admin.TabularInline):
    model = MissionCrewMember
    extra = 1
    fields = ('astronaut', 'role', 'order')
    autocomplete_fields = ['astronaut']

# 修改 MissionDetailAdmin 类
@admin.register(MissionDetail)
class MissionDetailAdmin(SortableAdminBase, admin.ModelAdmin):
    list_display = ('mission_name', 'related_groups_count')
    
    # 添加字段配置，优化多对多字段的显示
    filter_horizontal = ('articles', 'new_related_groups', 'crew_members', 'institutions')
    
    # 为外键字段添加搜索功能
    autocomplete_fields = ['launch_site', 'article_group','new_related_groups']
    
    # 设置编辑页面的字段布局
    fieldsets = (
        ('基本信息', {
            'fields': ('mission',)
        }),
        ('关联内容', {
            'fields': ('launch_site',)
        }),
        ('文章关联', {
            'fields': ('article_group', 'articles')
        }),
    )
    
    inlines = [MissionCrewMemberInline, MissionInstitutionMemberInline, MissionDetailTaskRelationInline]
    
    def mission_name(self, obj):
        return obj.mission.mission_name
    
    mission_name.short_description = "任务名称"

    def related_groups_count(self, obj):
        return obj.new_related_groups.count()
    
    related_groups_count.short_description = "关联任务组数量"

@admin.register(TaskRelation)
class TaskRelationAdmin(admin.ModelAdmin):
    form = TaskRelationForm  # 使用自定义表单

    # 列表页显示的字段
    list_display = ('relation_id', 'name', 'description', 'related_missions_count')

    # 添加过滤器
    list_filter = ('name',)

    # 搜索框（支持按 name 和 description 搜索）
    search_fields = ('name', 'description')

    # 在编辑页面中显示的字段
    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'image_url'),  # 添加image_url字段
        }),
        ('关联任务', {
            'fields': ('related_missions',),
        }),
    )

    # 在列表页显示一个只读字段，用于显示关联任务的数量
    def related_missions_count(self, obj):
        return obj.related_missions.count()
    related_missions_count.short_description = '关联任务数量'

    # 优化多对多字段的选择界面
    filter_horizontal = ('related_missions',)

#@admin.register(MissionDetailTaskRelation)
class MissionDetailTaskRelationAdmin(admin.ModelAdmin):
    list_display = ('mission_detail', 'task_relation', 'order')
    ordering = ['order']
    def get_model_perms(self, request):
        """
        返回一个空的权限字典，以隐藏模型。
        """
        return {}

admin.site.register(MissionDetailTaskRelation, MissionDetailTaskRelationAdmin)

@admin.register(MissionBasicInfo)
class MissionBasicInfoAdmin(admin.ModelAdmin):
    list_display = ('mission', 'country', 'institution', 'rocket_name')
    readonly_fields = ('mini_tags_preview',)

    def mini_tags_preview(self, obj):
        if not obj.mini_tags:  # 检查 mini_tags 是否为空
            return "无标签"
    
        if not isinstance(obj.mini_tags, list):  # 确保 mini_tags 是列表类型
            return "标签格式无效"
    
        try:
            # 尝试生成预览内容
            return ", ".join([
                f"{tag.get('title', '未知标题')}: {tag.get('content', '无内容')}"
                for tag in obj.mini_tags
            ])
        except (TypeError, KeyError):
            # 如果出现异常，返回错误提示
            return "标签解析失败"

        
    mini_tags_preview.short_description = "标签预览"

@admin.register(MissionContent)
class MissionContentAdmin(admin.ModelAdmin):
    list_display = ('mission',)
    readonly_fields = ('content_preview',)

    def content_preview(self, obj):
        if not obj.content:  # 检查 content 是否为空
            return "无内容"
    
        if not isinstance(obj.content, list):  # 确保 content 是列表类型
            return "内容格式无效"
    
        try:
            # 尝试生成预览内容
            return "\n".join([
                f"{item.get('type', '未知类型')}: {item.get('content', '无内容')}"
                for item in obj.content
            ])
        except (TypeError, KeyError):
            # 如果出现异常，返回错误提示
            return "内容解析失败"
    content_preview.short_description = "内容预览"

# 自定义 Encyclopedia 的 Admin 界面
# 导入新模型
from .models import EncyclopediaGroup, EncyclopediaSection, EncyclopediaSectionItem

# 百科词条关联的内联编辑 - 支持拖拽排序
class EncyclopediaSectionItemInline(SortableInlineAdminMixin, admin.TabularInline):
    model = EncyclopediaSectionItem
    extra = 1
    # 重新添加 order 字段以支持拖拽排序
    fields = ('encyclopedia', 'order')
    autocomplete_fields = ['encyclopedia']
    # 添加正确的排序配置
    ordering = ['order']

# 百科内容组子部分的内联编辑 - 支持拖拽排序
class EncyclopediaSectionInline(SortableInlineAdminMixin, admin.TabularInline):
    model = EncyclopediaSection
    extra = 1
    fields = ('subtitle', 'edit_link')
    readonly_fields = ('edit_link',)
    # 确保排序字段正确
    ordering = ['order']
    
    def edit_link(self, obj):
        if obj.pk:
            url = reverse('admin:myapp01_encyclopediasection_change', args=[obj.pk])
            return format_html('<a href="{}" target="_blank">编辑词条 ({}个)</a>', url, obj.items.count())
        return "保存后可编辑"
    edit_link.short_description = '词条管理'

# 百科内容组子部分的独立Admin - 支持拖拽排序（注册但隐藏）
@admin.register(EncyclopediaSection)
class EncyclopediaSectionAdmin(SortableAdminBase, admin.ModelAdmin):
    list_display = ('id', 'group_link', 'subtitle', 'items_count')
    # 移除时间字段过滤
    list_filter = ('group',)
    search_fields = ('subtitle', 'group__title')
    inlines = [EncyclopediaSectionItemInline]
    
    # 隐藏模型，不在admin首页显示
    def has_module_permission(self, request):
        return False
    
    def group_link(self, obj):
        url = reverse('admin:myapp01_encyclopediagroup_change', args=[obj.group.pk])
        return format_html('<a href="{}">{}</a>', url, obj.group.title)
    group_link.short_description = '所属内容组'
    
    def items_count(self, obj):
        return obj.items.count()
    items_count.short_description = '词条数量'

# 重新注册EncyclopediaSection（替换原来的@admin.register装饰器）
# 删除这两行
# admin.site.unregister(EncyclopediaSection)
# admin.site.register(EncyclopediaSection, EncyclopediaSectionAdmin)

# 百科内容组的Admin - 支持拖拽排序
@admin.register(EncyclopediaGroup)
class EncyclopediaGroupAdmin(SortableAdminBase, admin.ModelAdmin):
    # 移除时间字段显示
    list_display = ('id', 'title', 'sections_count', 'total_items_count')
    search_fields = ('title', 'description')
    # 移除时间字段过滤
    # list_filter = ('created_at', 'updated_at')
    ordering = ['title']  # 改为按标题排序
    inlines = [EncyclopediaSectionInline]
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description')
        }),
    )
    
    def sections_count(self, obj):
        return obj.sections.count()
    sections_count.short_description = '子部分数量'
    
    def total_items_count(self, obj):
        return sum(section.items.count() for section in obj.sections.all())
    total_items_count.short_description = '总词条数量'

# 更新Encyclopedia的Admin配置以支持自动完成
@admin.register(Encyclopedia)
class EncyclopediaAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'type', 'alias', 'tags')
    search_fields = ('name', 'alias', 'tags')
    # 移除时间字段过滤
    # list_filter = ('created_at', 'updated_at')
    # 改为按名称排序
    ordering = ('name',)
    
    # 设置编辑页面的字段布局
    fieldsets = (
        ('基本信息', {
            'fields': ('type', 'name', 'alias', 'url')
        }),
        ('分类和标签', {
            'fields': ('tags',)
        }),
        ('图片', {
            'fields': ('icon_url', 'cover_url')
        }),
        ('图片显示配置', {
            'fields': ('scaletype', 'colorfield')
        }),
        ('内容', {
            'fields': ('content', 'content_preview')
        }),
    )
    
    # 设置只读字段
    readonly_fields = ('content_preview',)
    
    def content_preview(self, obj):
        if not obj.content:
            return "无内容"
    
        if not isinstance(obj.content, list):
            return "内容格式无效"
    
        try:
            return "\n".join([
                f"{item.get('type', '未知类型')}: {item.get('content', '无内容')}"
                for item in obj.content
            ])
        except (TypeError, KeyError):
            return "内容解析失败"
    
    content_preview.short_description = "内容预览"

@admin.register(MissionStatus)
class MissionStatusAdmin(admin.ModelAdmin):
    list_display = ('mission', 'status', 'description', 'color_display')
    search_fields = ('mission__mission_name', 'status')
    list_filter = ('color',)
    
    def color_display(self, obj):
        return format_html(
            '<span style="background-color: {}; padding: 2px 8px; border-radius: 3px; color: white;">{}</span>',
            obj.color,
            obj.color
        )
    color_display.short_description = '颜色预览'


from .models import Astronaut
@admin.register(Astronaut)
class AstronautAdmin(admin.ModelAdmin):
    list_display = ('chinese_name', 'english_name', 'gender', 'country', 'status')
    list_filter = ('status', 'gender', 'country')
    search_fields = ('chinese_name', 'english_name')
    ordering = ('chinese_name',)

# 在文件顶部导入部分添加
from .models import LaunchSite

# 添加LaunchSite的管理界面配置
@admin.register(LaunchSite)
class LaunchSiteAdmin(SortableAdminBase, admin.ModelAdmin):
    list_display = ('id', 'name', 'order','active_pads', 'latitude_type', 'location_type')
    search_fields = ('name',)
    list_filter = ('latitude_type', 'location_type')
    readonly_fields = ('basic_info_preview', 'content_preview')
    
    def basic_info_preview(self, obj):
        if not obj.basic_info:  # 检查 basic_info 是否为空
            return "无基本信息"
    
        if not isinstance(obj.basic_info, list):  # 确保 basic_info 是列表类型
            return "基本信息格式无效"
    
        try:
            # 尝试生成预览内容
            return ", ".join([
                f"{item.get('title', '未知标题')}: {item.get('content', '无内容')}"
                for item in obj.basic_info
            ])
        except (TypeError, KeyError):
            # 如果出现异常，返回错误提示
            return "基本信息解析失败"
    
    basic_info_preview.short_description = "基本信息预览"
    
    def content_preview(self, obj):
        if not obj.content:  # 检查 content 是否为空
            return "无内容"
    
        if not isinstance(obj.content, list):  # 确保 content 是列表类型
            return "内容格式无效"
    
        try:
            # 尝试生成预览内容
            return "\n".join([
                f"{item.get('type', '未知类型')}: {item.get('content', '无内容')}"
                for item in obj.content
            ])
        except (TypeError, KeyError):
            # 如果出现异常，返回错误提示
            return "内容解析失败"
    
    content_preview.short_description = "内容预览"


# 自定义Admin站点标题和分组
admin.site.site_header = "HelloSpace 内容管理平台"
admin.site.site_title = "HelloSpace Admin"
admin.site.index_title = "欢迎使用 HelloSpace 内容管理平台"

# 在文件末尾添加

# 导入KnowledgeQuestion模型
from .models import KnowledgeQuestion

# 注册KnowledgeQuestion模型到admin
@admin.register(KnowledgeQuestion)
class KnowledgeQuestionAdmin(admin.ModelAdmin):
    # 列表页显示的字段
    list_display = ('id', 'question', 'correct_answer')
    
    # 搜索字段
    search_fields = ('question', 'option_a', 'option_b', 'option_c', 'option_d')
    
    # 过滤器
    list_filter = ('correct_answer',)
    
    # 排序方式
    ordering = ('id',)
    
    # 字段显示设置
    fieldsets = (
        ('题目信息', {
            'fields': ('question', 'correct_answer')
        }),
        ('选项', {
            'fields': ('option_a', 'option_b', 'option_c', 'option_d')
        }),
        ('解析', {
            'fields': ('explanation',)
        }),
    )



@admin.register(ArticleGroup)
class ArticleGroupAdmin(SortableAdminBase, admin.ModelAdmin):
    list_display = ('id', 'title', 'articles_count')
    search_fields = ('title', 'description')
    ordering = ['title']
    filter_horizontal = ('articles',)  # 使用水平过滤器选择文章
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description')
        }),
        ('关联文章', {
            'fields': ('articles',)
        }),
    )
    
    def articles_count(self, obj):
        return obj.articles.count()
    articles_count.short_description = '文章数量'
    inlines = []
    
    # 删除items_count方法，因为没有items字段
@admin.register(Institution)
class InstitutionAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'country', 'nature', 'order')
    search_fields = ('name', 'country', 'nature')
    list_filter = ('country', 'nature')
    ordering = ('order', 'name')
    
    # 添加内联编辑
    inlines = [InstitutionRelationInline]

